package com.yusp75.myexam.ui.browse

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.sqlite.db.SupportSQLiteQuery
import com.yusp75.myexam.com.yusp75.myexam.data.BrowsePagingSource
import com.yusp75.myexam.com.yusp75.myexam.data.QuestionRepository
import com.yusp75.myexam.com.yusp75.myexam.di.PrefManager
import com.yusp75.myexam.data.QuestionDao
import com.yusp75.myexam.data.QuestionWithStats
import com.yusp75.myexam.com.yusp75.myexam.data.QuestionFilter
import com.yusp75.myexam.data.ExerciseRecordDao
import com.yusp75.myexam.di.DataHolder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

class BrowseViewModel(
    private val questionDao: QuestionDao,
    private val exerciseRecordDao: ExerciseRecordDao,
    private val holder: DataHolder,
    private val prefManager: PrefManager,
    private val repository: QuestionRepository
) : ViewModel() {

    private val _filter = MutableStateFlow(QuestionFilter.ALL).apply {
        value = prefManager.browseFilter
    }
    val mFilter: StateFlow<QuestionFilter> = _filter.asStateFlow()

    private val _deleteResult = MutableLiveData<Boolean>()
    val deleteResult: LiveData<Boolean> = _deleteResult

    private val queryFlow: Flow<SupportSQLiteQuery> = _filter.map { filter ->
        when (filter) {
            QuestionFilter.ALL -> QuestionDao.buildFilterQuery(
                holder.bookId
            )

            QuestionFilter.FAVORITE -> QuestionDao.buildFilterQuery(
                holder.bookId,
                isFavorite = true
            )

            QuestionFilter.ONLYWRONG -> QuestionDao.buildFilterQuery(
                holder.bookId,
                onlyWrong = true
            )
        }
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    val pagedData: Flow<PagingData<QuestionWithStats>> = queryFlow
        .flowOn(Dispatchers.Default)  // 确保上游流在后台线程
        .flatMapLatest { query ->
            Pager(
                config = PagingConfig(
                    pageSize = 30,
                    prefetchDistance = 15,  // 设为pageSize的1/2
                    initialLoadSize = 30,
                    enablePlaceholders = false
                ),
                pagingSourceFactory = {
                    BrowsePagingSource(
                        questionDao = questionDao,
                        query = SimpleSQLiteQuery(query.sql)
                    )
                }
            ).flow.cachedIn(viewModelScope)
        }
        .flowOn(Dispatchers.IO)  // 确保分页操作在IO线程

    // 更新收藏状态
    fun updateFavorite(questionId: Int, isFavorite: Boolean) {
        viewModelScope.launch {
            questionDao.updateFavoriteStatus(questionId, isFavorite)
        }
    }

    // 移除题目的错误
    fun delRecord(questionId: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            exerciseRecordDao.delRecord(holder.bookId, questionId)
            _deleteResult.postValue(true)  // 使用postValue从后台线程更新
        }
    }

    // 类型过滤
    // 设置
    fun setFilter(idx: QuestionFilter) {
        _filter.value = idx

    }

    // 保存
    fun saveFilter() {
        prefManager.browseFilter = _filter.value
    }

    fun getFilter(): QuestionFilter {
        return prefManager.browseFilter
    }

    private fun createDynamicPager(
        query: SupportSQLiteQuery
    ): Pager<Int, QuestionWithStats> {
        return Pager(
            config = PagingConfig(
                pageSize = 20,
                prefetchDistance = 10,
                initialLoadSize = 40
            ),
            pagingSourceFactory = {
                //questionDao.queryFilterByBuilder(SimpleSQLiteQuery(query.sql))
                questionDao.getPagedQuestions()
            }
        )
    }

    //
}
